from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .models import *
from .pagination import MyPage
from .serializers import SpitSerializer


class SpitView(ModelViewSet):
    serializer_class = SpitSerializer
    queryset = Spit.objects.all()


    # 吐槽列表
    def list(self, request, *args, **kwargs):
        spit_list = self.get_queryset().filter(parent_id=None).all()
        print(spit_list)
        retSpitList = []

        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            for spit in spit_list:
                flag_collect = redis_conn.hget("collect_%s" % user.id, str(spit.id))
                flag_thumbup = redis_conn.hget("thumbup_%s" % user.id, str(spit.id))
                if flag_collect:
                    spit.collected = True
                if flag_thumbup:
                    spit.hasthumbup = True

                retSpitList.append(spit)
        else:
            retSpitList = spit_list

        s = self.get_serializer(instance=retSpitList, many=True)
        return Response(s.data)

    # 收藏
    @action(methods=['put'], detail=True)
    def collect(self, request, pk):
        user = request.user
        spit = Spit.objects.get(id=pk)
        collect = spit.collected
        if not user.is_authenticated:
            return Response({'message': '请登录后重试'}, status=status.HTTP_401_UNAUTHORIZED)
        redis_conn = get_redis_connection('spit')
        spit_thumbup = redis_conn.hkeys('thumbup_%d' % user.id)
        spit_thumbup = [spit.decode() for spit in spit_thumbup]
        print(spit_thumbup)

        if pk in spit_thumbup:
            redis_conn.hdel('thumbup_%d' % user.id, pk)
            spit.thumbup -= 1
            spit.save()
            return Response({"message": "取消点赞成功", "success": True})
        else:
            redis_conn.hset('thumbup_%d' % user.id, pk, 1)
            spit.thumbup += 1
            spit.save()
            return Response({"message": "点赞成功", "success": True})

    # 点赞
    @action(methods=['put'], detail=True)
    def updatethumbup(self, request, pk):
        user = request.user
        spit = Spit.objects.get(id=pk)
        hasthumbup = spit.hasthumbup
        if not user.is_authenticated:

            return Response({'message': '请登录后重试'}, status=status.HTTP_401_UNAUTHORIZED)
        redis_conn = get_redis_connection('spit')
        spit_thumbup = redis_conn.hkeys('thumbup_%d' % user.id)
        spit_thumbup = [spit.decode() for spit in spit_thumbup]
        print(spit_thumbup)

        if pk in spit_thumbup:
            redis_conn.hdel('thumbup_%d' % user.id, pk)
            spit.thumbup -= 1
            spit.save()
            return Response({"message": "取消点赞成功", "success": True})
        else:
            redis_conn.hset('thumbup_%d' % user.id, pk, 1)
            spit.thumbup += 1
            spit.save()
            return Response({"message": "点赞成功", "success": True})

    # 吐槽详情
    def retrieve(self, request, *args, **kwargs):
        spit = self.get_object()
        spit.visits += 1
        spit.save()
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            flag_collect = redis_conn.hget("collect_%d" % user.id, user.pk)
            flag_thumbup = redis_conn.hget("thumbup_%d" % user.id, user.pk)
            if flag_collect:
                spit.collected = True
            if flag_thumbup:
                spit.hasthumbup = True

        s = self.get_serializer(instance=spit)
        return Response(s.data)

    # 吐槽评论
    @action(methods=['get'], detail=True)
    def children(self, request, pk):
        spit_list = self.get_queryset().filter(parent=pk).order_by('publishtime')
        retSpitList = []

        try:
            user = self.request.user
            print(user.id, user.username)
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            for spit in spit_list:
                flag_collect = redis_conn.hget("collect_%s" % user.id, str(spit.id))
                flag_thumbup = redis_conn.hget("thumbup_%s" % user.id, str(spit.id))
                if flag_collect:
                    spit.collected = True
                if flag_thumbup:
                    spit.hasthumbup = True
                spit.userid = user.id
                spit.avatar = user.avatar
                spit.nickname = user.nickname
                retSpitList.append(spit)
            # retSpitList['userid'] = user.id
            print(retSpitList)
        else:
            retSpitList = spit_list

        s = self.get_serializer(instance=retSpitList, many=True)

        print(s.data)
        return Response(s.data)




# # class SpitMsgView(RetrieveAPIView):
# #     serializer_class = SpitListSerializer
# #     queryset = Spit.objects.all().order_by('id')
# #     pagination_class = MyPage
#
#
# class SpitPingView(ListAPIView):
#     serializer_class = SpitListSerializer
#     queryset = Spit.objects.all().order_by('id')
#     pagination_class = MyPage
#
#
# class SpitCollectView(APIView):
#     def post(self, request):
#         id = self.kwargs.get('id')
#         spit = Spit.objects.get(id=id)
#         spit.collected = True
#         spit.save()
#         Response(
#             data={'success': spit.collected}
#         )
#

